package org.example.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.yaml.YamlUtil;

import java.nio.charset.StandardCharsets;

public class ConfigUtils {

    private static Props props;

    /**
     * 加载配置对象
     * @param tClass
     * @param prefix
     * @return
     * @param <T>
     */
    public static <T> T loadConfig(Class<T> tClass, String prefix){
        System.out.println(Thread.currentThread().getName() + "执行ConfigUtils类的loadConfig(tClass,prefix)方法"
                            + "参数有：" + tClass.toString() + "|" + prefix);
        return loadConfig(tClass,prefix,"");
    }

    /**
     * 加载配置对象，支持区分环境
     * @param tClass
     * @param prefix
     * @param environment
     * @return
     * @param <T>
     */
    public static <T> T loadConfig(Class<T> tClass, String prefix, String environment) {
        System.out.println(Thread.currentThread().getName() + "执行ConfigUtils类的loadConfig(tClass,prefix,environment)"
                            + "参数有：" + tClass.toString() + "|" + prefix + "|" + environment);

        StringBuilder configFileBuilder = new StringBuilder("application");
        if (StrUtil.isNotBlank(environment)){
            configFileBuilder.append("-").append(environment);
        }
        configFileBuilder.append(".properties");
        if (props == null){

            props = new Props(configFileBuilder.toString(),StandardCharsets.UTF_8);
            //在配置文件变更时自动加载
            props.autoLoad(true);
        }
        //System.out.println(props.getStr("rpc.serverPort"));
        //保证配置文件路径不变，可以实现配置文件自动更新
        return props.toBean(tClass,prefix);
    }

    /**
     * 处理yml和yaml文件
     * @param tClass
     * @param prefix
     * @param environment
     * @return
     * @param <T>
     */
    public static <T> T loadYmlConfig(Class<T> tClass, String prefix, String environment) {
        StringBuilder configFileBuilder = new StringBuilder("application");
        if (StrUtil.isNotBlank(environment)){
            configFileBuilder.append("-").append(environment);
        }
        String configFile = configFileBuilder.append(".yml").toString();
        Dict dict = YamlUtil.loadByPath(configFile);
        if (!dict.isEmpty()){
            return BeanUtil.copyProperties(dict.getBean(prefix),tClass);
        }
        configFile = StrUtil.subBefore(configFile, ".", true) + ".yaml";
        dict = YamlUtil.loadByPath(configFile);
        return BeanUtil.copyProperties(dict.getBean(prefix),tClass);
    }
}
